#include "connector.h"

// using namespace easyWebServer;

namespace dxy::easyWebServer
{

Connector::Connector()
{

}

Connector::~Connector()
{

}

size_t Connector::sendMsg(int fd, const std::string & src)
{
    if(fd < -1) __throw_logic_error("fd error"); 
    size_t len = send(fd, src.c_str(), src.size(), 0);
    if(len == -1) __throw_logic_error("write error");
    return len;
}

size_t Connector::existFile(const std::string & filePath)
{
    std::string in = "." + filePath;
    int ret = access(in.c_str(), F_OK);
    if(ret != 0)
    {
        return -1;
    }
    struct stat fileStat;
    stat(in.c_str(), &fileStat);
    return fileStat.st_size;
}

size_t Connector::sendFile(int fd, const std::string & filePath, size_t size)
{
    std::string in = "." + filePath;
    int filefd = open(in.c_str(), O_RDONLY);
    ssize_t len = sendfile(fd, filefd, nullptr, size);
    close(filefd);
    return len;
}

std::string Connector::recvLine(int fd)
{
    std::string out;
    char c = '\0';
    while(1)
    {
        if(recv(fd, &c, 1, 0) != 1)
        {
            __throw_logic_error("recv error");
        }
        if(c == '\r')
        {
            recv(fd, &c, 1, 0);
            break;
        }
        out += c;
    }
    return out;
}

void Connector::recvMsg(int fd, uint8_t * src, size_t size)
{
    if(recv(fd, src, size, 0) == -1)
    {
        __throw_logic_error("recv error");
    }
}




}